package com.shi.controller;

import com.shi.entity.DiscussPost;
import com.shi.entity.Page;
import com.shi.service.ElasticsearchService;
import com.shi.service.LikeService;
import com.shi.service.UserService;
import com.shi.utils.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 石泉
 * @version 1.0
 * @date 21/08/24 17:58
 */
@Controller
public class SearchController implements CommunityConstant {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @GetMapping("/search")
    public String search(String keyword, Page page, Model model) {
        // 搜索帖子
        Map<String, Object> searchResult = elasticsearchService.searchDiscussPost(keyword, page.getOffset(), page.getLimit());

        // 聚合数据
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (searchResult != null) {
            for (DiscussPost post : (List<DiscussPost>) searchResult.get("list")){
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", post);
                // 作者
                map.put("user", userService.findUserById(post.getUserId()));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("keyword", keyword);


        // 分页信息
        page.setPath("/search?keyword=" + keyword);
        if(searchResult.get("count") == null){
            page.setRows(0);
        }else{
            Long rows = (Long) searchResult.get("count");
            page.setRows(rows.intValue());
        }

        return "/site/search";
    }
}
